import React, { useEffect, useRef, useState } from 'react';
import { history } from 'umi';
type Props = {};

export default function index({}: Props) {
  let [name, setname] = useState('');
  let [phone, setphone] = useState('');
  let [yanzheng, setyanzheng] = useState('');
  let [pph, setpph] = useState('13112345678');
  let [jiny, setjiny] = useState(true);
  let [yan, setyan] = useState('');
  let [zt, setzt] = useState(false);
  const timerCount = 10; // 默认10秒
  const [count, setCount] = useState(timerCount);
  const timerRef = useRef(null); // 记录时间的定时器
  const cutCount = () => {
    setCount((prevState) => prevState - 1); // 为什么这里要用函数- 如果用count 发现count闭包了 不会发生变化了
  };
  const sendCode = () => {
    switch (true) {
      case name.length === 0:
        alert('昵称不能为空');
        break;
      case phone !== pph:
        alert('手机号格式不对');
        break;
      case name.length > 0 && phone === pph:
        // 要发送验证码
        cutCount();
        timerRef.current = setInterval(cutCount, 1000);
        let charactors = '1234567890';
        let value = '',
          i;
        for (let j = 1; j <= 4; j++) {
          i = parseInt(10 * Math.random());
          value = value + charactors.charAt(i);
        }
        console.log(value);
        setyan(value);
        alert('验证码为' + value);
        break;
    }
  };
  useEffect(() => {
    if (count === 0) {
      clearInterval(timerRef.current); // 清空定时器
      setCount(timerCount); // 重新将技术器设置为60秒
    }
  }, [count]);
  return (
    <div>
      <div>手机号登录</div>
      昵称：
      <input
        type="text"
        placeholder="请输入昵称"
        value={name}
        onChange={(e) => {
          setname(e.target.value);
        }}
      />
      <br />
      手机号：
      <input
        type="text"
        value={phone}
        placeholder="请输入手机号"
        onChange={(e) => {
          setphone(e.target.value);
        }}
      />
      <br />
      验证码：
      <input
        type="text"
        placeholder="请输入验证码"
        value={yanzheng}
        onChange={(e) => {
          setyanzheng(e.target.value);
          if (e.target.value.length <= 0) {
            setjiny(true);
          } else {
            setjiny(false);
          }
          console.log();
        }}
      />{' '}
      <button
        onClick={count === timerCount ? sendCode : null}
        disabled={count < timerCount}
      >
        {count === timerCount ? '发送验证码' : `还剩${count}秒`}
      </button>
      <br />
      <button
        onClick={() => {
          if (name.length > 0 && phone === pph && yanzheng === yan) {
            sessionStorage.setItem('userid', '11111');
            history.push({
              pathname: '/xl4',
              state: name,
            });
          } else {
            alert('验证码错误!');
          }
        }}
        disabled={jiny}
      >
        登录
      </button>
    </div>
  );
}
